package com.base.moduleAI.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.core.common.http.response.AjaxResult;
import com.base.core.common.utils.MarkdownToHtmlUtils;
import com.base.core.common.utils.OkHttpClientUtil;
import com.base.moduleAI.entity.dto.AIPublishArticleDTO;
import com.base.moduleAI.service.IAIService;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AIServiceImpl implements IAIService {

    @Resource
    private  CsdnArticlePublisher  csdnArticlePublisher;


    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public AjaxResult publishCsdnBlog(AIPublishArticleDTO articleDTO) {
        String response = null; // 将response声明移到外部

        try {

            String requestBody=this.buildRequestBody(articleDTO);

            log.debug("CSDN请求体: {}", requestBody);
            // 2. 创建并配置HTTP请求
            HttpPost httpPost = csdnArticlePublisher.createHttpPost(requestBody);
            // 3. 执行请求
            response = csdnArticlePublisher.executeRequest(httpPost);
            log.info("CSDN文章发布成功: {}", response);
        } catch (RuntimeException e) {
            log.error("构建请求体失败: {}", e.getMessage());
            return AjaxResult.error("构建请求体失败: " + e.getMessage());
        } catch (IOException e) {
            log.error("CSDN API请求异常: {}", ExceptionUtils.getStackTrace(e));
            return AjaxResult.error("发布请求失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("CSDN文章发布异常: {}", ExceptionUtils.getStackTrace(e));
            return AjaxResult.error("发布失败: " + e.getMessage());
        }

        return AjaxResult.success(response);
    }




    private String buildRequestBody(AIPublishArticleDTO articleDTO) throws Exception {
        //调用DeepSeek接口生成文章内容
        String result = DeepSeekChatClient.callDeepSeekChat(articleDTO.getContent());
        log.info("DeepSeek返回结果: " + result);
        JsonNode rootNode = mapper.readTree(result);
        String content = rootNode.path("choices")
                .get(0)
                .path("message")
                .path("content")
                .asText();
        System.out.println(content);
        //将content内容转换成html格式
        String htmlcontent= MarkdownToHtmlUtils.markdownToHtml(content);
        List<String> tags = new ArrayList<>();
        tags.add("intellij-idea");
        System.out.println(String.join(",", tags));
        return csdnArticlePublisher.buildPublishRequest(articleDTO, htmlcontent);
    }
}
